<template>
	<view class="container">
		<TopNav title="在线时长统计"></TopNav>
		<view class="">
			<text class="f-s14 f-w500 line-height20" style="color:#27272C;">注：该统计为工作状态为“工作中”的时间</text>
		</view>
		<view class="p-tb12 p-lr10 bg-white radius m-t12">
			<view class="flex">
				<YearPicker v-model="year" class="m-r10"></YearPicker>
				<MonthPicker v-model="month" :year="year" @input="handleMonthChange"></MonthPicker>
			</view>
			<view class="p-tb14 f-w600 f-s24 line-height34 text-drak">
				<text>{{year}}年{{month}}月</text>
			</view>
			<view class="calendar">
				<view class="weekdays">
					<view v-for="day in weekdays" :key="day">{{ day }}</view>
				</view>
				<view class="days">
					<view class="days-item" v-for="(day, index) in days" :key="index"
						:class="{'other-month': !day.isCurrentMonth,'service-day':day.duration}">
						<view class="days-item-dot" v-if="day.duration"
							:class="{'days-item-dot-red':day.duration>10}"></view>
						<text class="date">{{ day.date }}</text>
						<text class="time" v-if="day.duration">{{day.duration}}小时</text>
					</view>
				</view>
			</view>
		</view>
		<view class="flex align-center m-t10 f-w400 line-height17 f-s12" style="color:#27272C;">
			<text class="m-r10" style="color:#585D66;">说明</text>
			<view class="dot m-r5"></view>
			<text>在线未满10小时</text>
			<view class="dot-red m-r5 m-l12"></view>
			<text>在线10小时及以上</text>
		</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	import YearPicker from "@/components/picker-year/index.vue"
	import MonthPicker from "@/components/picker-month/index.vue"
	import {
		integral,
		integralList
	} from '@/api/index/data.js'
	export default {
		components: {
			YearPicker,
			MonthPicker
		},
		data() {
			return {
				month: dayjs().format('M'),
				year: new Date().getFullYear(),
				currentDate: dayjs(),
				weekdays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				days: [],
				queryParams: {
					page: 1,
					limit: 31,
					date: ''
				}
			};
		},
		onLoad() {
			this.generateCalendar();
			this.getList()
		},
		methods: {
			minutesToHours(minutes) {
				// 严格验证 - 仅接受数字或数字字符串
				if (typeof minutes === 'boolean' ||
					minutes === null ||
					minutes === undefined ||
					isNaN(minutes) ||
					(typeof minutes === 'string' && minutes.trim() === '')) {
					return null;
				}

				const mins = Number(minutes);
				if (isNaN(mins)) return null;

				const hours = mins / 60;
				return hours % 1 === 0 ? hours : Math.floor(parseFloat(hours));
			},
			getList() {
				this.queryParams.date = this.year + '-' + this.month
				integralList(this.queryParams).then(res => {
					let {
						data: {
							list,
							count,
							total
						}
					} = res
					this.total = count || 0
					this.pageTotal = total || 0
					if (this.queryParams.page === this.pageTotal) this.loadmoreStatus = 'nomore'
					if (this.queryParams.page === 1) {
						this.list = list
					} else if (this.queryParams.page < this.pageTotal) {
						this.list = this.list.concat(list)
					}
					this.days.forEach((item,index)=>{
						let findResult = this.list.find(findItem=>findItem.date === item.fullDate)
						if(findResult){
							this.$set(this.days[index],'duration',this.minutesToHours(findResult.duration))
							// item.duration = this.minutesToHours(findResult.duration)
						}
					})
				})
			},
			checkDayService(date) {
				// console.log('date: ',date);
				// return index < 20 && index > 9
				return false
			},
			handleMonthChange(month) {
				this.currentDate = `${this.year}-${month}`;
				this.getList()
				this.generateCalendar();
			},
			 padZero(num) {
				// 验证输入是否为有效数字
				if (isNaN(num) || num === null || num === undefined) {
					return null;
				}
			
				// 转换为字符串并使用 padStart 补零
				return String(num).padStart(2, '0');
			},
			generateCalendar() {
				const startOfMonth = dayjs(this.currentDate).startOf('month');
				const endOfMonth = dayjs(this.currentDate).endOf('month');
				const startDay = startOfMonth.day() || 7; // 获取当前月1号是周几，dayjs中周日是0，周一是1，依此类推
				const endDay = endOfMonth.date(); // 获取当前月的最后一天是几号

				const days = [];

				
				// 添加上个月的最后几天
				for (let i = startDay - 1; i > 0; i--) {
					days.push({
						date: startOfMonth.subtract(i, 'day').date(),
						fullDate: `${dayjs(startOfMonth).subtract(1, 'month').format('YYYY-MM')}-${this.padZero(i)}`,
						isCurrentMonth: false
					});
				}

				// 添加当前月的所有日期
				for (let i = 1; i <= endDay; i++) {
					days.push({
						date: i,
						fullDate: `${dayjs(startOfMonth).format('YYYY-MM')}-${this.padZero(i)}`,
						isCurrentMonth: true
					});
				}

				// 添加下个月的前几天
				const remainingDays = 42 - days.length; // 6行 * 7列 = 42个格子
				for (let i = 1; i <= remainingDays; i++) {
					days.push({
						date: i,
						fullDate: `${dayjs(startOfMonth).add(1, 'month').format('YYYY-MM')}-${this.padZero(i)}`,
						isCurrentMonth: false
					});
				}
				this.days = days;
			}
		}
	};
</script>

<style scoped lang="scss">
	.container {
		padding: 20rpx 24rpx;
	}

	.calendar {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.header {
		margin-bottom: 20px;
	}

	.weekdays {
		display: flex;
		justify-content: space-around;
		width: 100%;
		margin-bottom: 24px;
		font-weight: 500;
		font-size: 24rpx;
		color: #202020;
		line-height: 34rpx;
	}

	.days {
		width: 100%;
		display: grid;
		grid-template-rows: repeat(6, 112rpx);
		/* 6行 */
		grid-template-columns: repeat(7, 1fr);
		/* 7列 */
		gap: 8rpx;

		/* 子元素之间的间隔 */
		.days-item {
			text-align: center;
			padding: 12px 0;
			border-radius: 8rpx;
			display: flex;
			flex-direction: column;
			width: 100%;
			position: relative;

			.days-item-dot {
				position: absolute;
				top: 10rpx;
				left: calc(50% - 5rpx);
				width: 10rpx;
				height: 10rpx;
				border-radius: 50%;
				background: #00AE52;
			}

			.days-item-dot-red {
				background: #FE3F59;
			}

			.date {
				font-weight: 500;
				font-size: 28rpx;
				color: #202020;
				line-height: 40rpx;
			}

			.time {
				font-weight: 400;
				font-size: 22rpx;
				color: #909399;
				line-height: 32rpx;

			}

		}

		.other-month {
			.date {
				color: #909399;
			}
		}

		.service-day {
			background: #F5F6F7;
		}

	}

	.dot {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		background: #00AE52;
	}

	.dot-red {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		background: #FE3F59;
	}
</style>